//
//  ManageController
//  GroceryStoryboards
//
//  Created by jose on 10/03/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "ManageController.h"
#import "FirstStepController.h"
#import "SecondStepController.h"
#import "ThirdStepController.h"
#import "FourthStepController.h"
#import "FinalStepViewController.h"

#import "Unities.h"

@interface ManageController ()

@end

@implementation ManageController

@synthesize groceryLabel, mainScrollView, firstSubstring, secondSubstring, thirdSubstring, fourthSubstring;
@synthesize unityIndex, item;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.screenName = @"Manage Screen";

    UIStoryboard *story = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    
    FirstStepController *first = [story instantiateViewControllerWithIdentifier:@"FirstStep"];
    [self addChildViewController:first];
    [first.view setFrame:CGRectMake(0, 0, first.view.frame.size.width, first.view.frame.size.height)];
    [self.mainScrollView addSubview:first.view];

    NSLog(@"The frame of the first is %f, %f and the size %f, %f" , first.view.frame.origin.x, first.view.frame.origin.y, first.view.frame.size.width, first.view.frame.size.height);
    
    SecondStepController *second = [story instantiateViewControllerWithIdentifier:@"SecondStep"];
    [self addChildViewController:second];
    [second.view setFrame:CGRectMake(320, 0, second.view.frame.size.width, second.view.frame.size.height)];
    [self.mainScrollView addSubview:second.view];
    
    ThirdStepController *third = [story instantiateViewControllerWithIdentifier:@"ThirdStep"];
    [self addChildViewController:third];
    [third.view setFrame:CGRectMake(640, 0, third.view.frame.size.width, third.view.frame.size.height)];
    [self.mainScrollView addSubview:third.view];
    
    FourthStepController *fourth = [story instantiateViewControllerWithIdentifier:@"FourthStep"];
    [self addChildViewController:fourth];
    [fourth.view setFrame:CGRectMake(960, 0, fourth.view.frame.size.width, fourth.view.frame.size.height)];
    [self.mainScrollView addSubview:fourth.view];
    
    FinalStepViewController *final = [story instantiateViewControllerWithIdentifier:@"FinalStep"];
    [self addChildViewController:final];
    [final.view setFrame:CGRectMake(1280, 0, fourth.view.frame.size.width, fourth.view.frame.size.height)];
    [self.mainScrollView addSubview:final.view];
    

    if (item != nil) {
        
        isNew = NO;
        firstSubstring = item.itemName;
        secondSubstring = item.itemUnity;
        for (int i = 0; i < [[Unities singularUnities] count]; i ++) {
            if ([secondSubstring isEqualToString:[[Unities singularUnities] objectAtIndex:i]] ||
                [secondSubstring isEqualToString:[[Unities pluralUnities] objectAtIndex:i]]) {
                self.unityIndex = i;
                break;
            }
        }
        thirdSubstring = item.itemQuantity;
        fourthSubstring = item.itemPrice;
        
        [first.nameTextField setText:firstSubstring];
        first.nameString = firstSubstring;
        [second.unityText setText:secondSubstring];
        second.unityString = secondSubstring;
        [third.amountTextField setText:thirdSubstring];
        third.amountString = thirdSubstring;
        [fourth.priceTextField setText:fourthSubstring];
        fourth.priceString = fourthSubstring;
        
        [self buildLabel];
    } else {
        
        isNew = YES;
        firstSubstring = @"";
        secondSubstring = @"";
        thirdSubstring = @"";
        fourthSubstring = @"";
        item = [[Item alloc] init];
        item.itemId = [[NSUUID UUID] UUIDString];
        item.itemAdditionDate = [NSDate date];
        item.itemModifiedDate = [NSDate date];
    }
    
    
    [self.mainScrollView setContentSize:CGSizeMake(320 * [self.childViewControllers count], self.mainScrollView.frame.size.height)];
    [self.mainScrollView setScrollEnabled:YES];
    
    UIViewController *vc = [[self childViewControllers] objectAtIndex:0];
    if ([vc respondsToSelector:@selector(showControls)])
        [vc performSelector:@selector(showControls)];
}

-(void)viewWillAppear:(BOOL)animated {
    
    [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^(void) {
        
        self.backLabel.transform = CGAffineTransformMakeRotation(270 * M_PI / 180.0);
        [self.backLabel setFrame:CGRectMake(self.backLabel.frame.origin.x - 15, self.backLabel.frame.origin.y - 10,
                                            self.backLabel.frame.size.width, self.backLabel.frame.size.height)];
    }completion:^(BOOL res) {
        
    }];
}

- (void)buildLabel {
    
    if ([self.thirdSubstring integerValue] <= 1)
        self.secondSubstring = [[Unities singularUnities] objectAtIndex:self.unityIndex];
    else
        self.secondSubstring = [[Unities pluralUnities] objectAtIndex:self.unityIndex];
    
    if (([self.firstSubstring length] > 0) && ([self.secondSubstring length] > 0))
        self.groceryLabel.text = [NSString stringWithFormat:@"%@  %@  %@  %@", self.thirdSubstring, self.secondSubstring, NSLocalizedString(@"OF", nil), self.firstSubstring];
    else
        self.groceryLabel.text = [NSString stringWithFormat:@"%@  %@  %@", self.thirdSubstring, self.secondSubstring, self.firstSubstring];
    
    if ([self.fourthSubstring length] > 0)
        self.groceryLabel.text = [NSString stringWithFormat:@"%@ %@ %@%@", self.groceryLabel.text, NSLocalizedString(@"FOR", nil), self.fourthSubstring, [[NSUserDefaults standardUserDefaults] valueForKey:kCurrencyKey]];
}

- (IBAction)backPressed:(UIButton *)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)nextStep {
    
    [self.mainScrollView scrollRectToVisible:CGRectMake(
                                                        self.mainScrollView.contentOffset.x + 320,
                                                        self.mainScrollView.frame.origin.y,
                                                        self.mainScrollView.frame.size.width,
                                                        self.mainScrollView.frame.size.height) animated:YES];
}

#pragma mark - ScrollView Delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    for (UIViewController *vc in self.childViewControllers)
        if ([vc respondsToSelector:@selector(hideControls)])
            [vc performSelector:@selector(hideControls)];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (((scrollView.contentOffset.x / scrollView.frame.size.width) -
         ((int) (scrollView.contentOffset.x / scrollView.frame.size.width))) == 0) {
        
        NSLog(@"The offset is: %f and the widht: %f", scrollView.contentOffset.x, scrollView.frame.size.width);
        NSLog(@"Page number %d", (int) (scrollView.contentOffset.x / scrollView.frame.size.width));
        UIViewController *vc = [[self childViewControllers] objectAtIndex:(int) (scrollView.contentOffset.x / scrollView.frame.size.width)];
        if ([vc respondsToSelector:@selector(showControls)])
        [vc performSelector:@selector(showControls)];
    }
}

#pragma mark - First Step

- (void)typingString:(NSString *)string {
    
    self.firstSubstring = string;
    
    [self buildLabel];
}

#pragma mark - Second Step

- (void)unitySelected:(NSNumber *)index {
    
    self.unityIndex = [index integerValue];
    
    [self buildLabel];
}


#pragma mark - Third Step

- (void)amountSelected:(NSString *)string {
    
    self.thirdSubstring = string;
    
    [self buildLabel];
}
- (void)typingAmount:(NSString *)string {
    
    self.thirdSubstring = string;
    
    [self buildLabel];
}

#pragma mark - Fourth Step

- (void)typingPrice:(NSString *)string {
    
    self.fourthSubstring = string;
    
    [self buildLabel];
}

#pragma mark - Final Step

- (void)addGrocery {
    
    NSString *errorMessage = @"";
    if ([firstSubstring length] <= 0)
        errorMessage = [errorMessage stringByAppendingString:NSLocalizedString(@"ERROR ITEM NAME", nil)];
    
    if([secondSubstring length] <= 0)
        errorMessage = [errorMessage stringByAppendingString:NSLocalizedString(@"ERROR ITEM UNITY", nil)];
    
    if ([thirdSubstring length] <= 0)
        errorMessage = [errorMessage stringByAppendingString:NSLocalizedString(@"ERROR ITEM AMOUNT", nil)];
        
    if ([errorMessage length] > 0) {
        
        errorMessage = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"ERROR INFO NEEDED", nil), errorMessage];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ERROR TITLE", nil) message:errorMessage delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
        [alert show];
    } else {
        
        item.itemName = firstSubstring;
        item.itemUnity = secondSubstring;
        item.itemQuantity = thirdSubstring;
        
        item.itemPrice = fourthSubstring;
        
        item.itemModifiedDate = [NSDate date];
        
        [ItemsController upsertItem:item];
        
        NSString *type, *value = self.groceryLabel.text;
        if (isNew)  type = @"item_added";
        else        type = @"item_edited";
        
        
        [[[GAI sharedInstance] defaultTracker] send:
         [[GAIDictionaryBuilder createEventWithCategory:type
                                                 action:@"button_press"
                                                  label:value
                                                  value:nil]
          build]];
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    [self restart];
}

- (void)restart {
    
    [self.mainScrollView scrollRectToVisible:CGRectMake(0,
                                                        self.mainScrollView.frame.origin.y,
                                                        self.mainScrollView.frame.size.width,
                                                        self.mainScrollView.frame.size.height) animated:YES];
}

@end
